package com.livedocumentation.client.webservices.comments;

import java.util.ArrayList;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livedocumentation.client.model.Comment;
import com.livedocumentation.client.model.User;
import com.livedocumentation.client.web.comments.CommentsList;
import com.livedocumentation.client.web.description.FeaturePanel;
import com.livedocumentation.client.webservices.ConvertJsonp;

public class RequestListComments {

	// http://jsonpfy.livedocumentation.appspot.com/ListDataService
	// ?kind=Comment
	// &filterField1=projectIDg&filterValue1=Projectnection
	// &filterField2=classPath&filterValue2=com.projectnection.client.Entities.EntityPage
	// &sortField=date&sortDirection=desc

	private static String url = "http://jsonpfy.livedocumentation.appspot.com/ListDataService";

	public static void getJsonpRequest(String projectID, String classPath) {

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(10000);

		String urlList = url + "?kind=Comment"
				+ "&filterField1=projectID&filterValue1=" + projectID
				+ "&filterField2=classPath&filterValue2=" + classPath;

		// urlList += "&sortField=date";
		urlList += "&sortDirection=desc";

		jsonp.requestObject(urlList, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject entries = new JSONObject(feed);

				ArrayList<Comment> comments = new ArrayList<Comment>();

				for (int i = 0; i < entries.size(); i++) {

					JSONObject entry = (JSONObject) entries.get(i + "");

					Comment comment = convertToComment(entry);

					comments.add(comment);
				}

				FeaturePanel.vpCommentsList.clear();
				FeaturePanel.vpCommentsList.add(new CommentsList(comments));
			}
		});
	}

	private static Comment convertToComment(JSONObject obj) {

		Comment comment = new Comment();

		comment.setCommentID(ConvertJsonp.convertToString(obj.get("ID")));

		comment.setProjectID(ConvertJsonp.convertToString(obj.get("projectID")));

		comment.setClassPath(ConvertJsonp.convertToString(obj.get("classPath")));

		User facebookUser = new User();

		facebookUser.setFacebookID(ConvertJsonp.convertToString(obj
				.get("facebookUserID")));

		facebookUser.setFacebookName(ConvertJsonp.convertToString(obj
				.get("username")));

		facebookUser.setEmail(ConvertJsonp.convertToString(obj.get("email")));

		comment.setFacebookUser(facebookUser);

		// liveFeed.setLiveFeedDate(new Date(new Long(obj.get("liveFeedDate")
		// .toString().replaceAll("\"", ""))));

		comment.setDescription(ConvertJsonp.convertToString(obj
				.get("description")));

		return comment;
	}
}
